﻿$(document).ready(function () {

    g5.init();
    $("#finishedPL").bind(touchEndEvent, g5.saveProductsToList);
    $("#revertPL").bind(touchEndEvent, function (e) {
        e.preventDefault(); 
        g5.fillProductsList(); 
        });

    //g5.fillProductsList();
});

var g5 = {
    toBuy: [],
    knownProducts: [],

    init: function () {
        $.getJSON("../data/artikelen.txt", function (data) {
            $.each(data, function () {
                g5.knownProducts.push(
                {
                    id: this.id,
                    name: this.name,
                    category: this.category,
                    count: this.count
                });
            });
           // alert("has knownProducts.length : " + g5.knownProducts.length);
        });
        //        alert("has localStorage : " + $has.localStorage);
        //        alert("has knownProducts.length : " + g5.knownProducts.length);
    },
    saveProductsToList: function (e) {
        e.preventDefault();
        alert('saving to list...');
    }
    ,
    fillProductsList: function () {
        
        $("#listAvailableProducts").empty();
        $.each(g5.knownProducts, function () {
            var newItem = $("#template-products").clone();

            // Now fill in the fields with the data
           // var currentProduct = newItem.find(".prodToEdit");
            newItem.find(".prodToEdit").text(this.name);
            newItem.find(".prodToEdit").next().text(false);
            newItem.find(".prodToEdit").next().next().text(this.count);

            // And add the new list item to the page
            newItem.children().appendTo("#listAvailableProducts");

        });
        $("#listAvailableProducts .prodToEdit").bind(touchEndEvent, function (e) {
            e.preventDefault();
            // showProductChange(e);
            currentProduct = $(this);
            $("#popPrepareProduct").data("kendoMobilePopOver").openFor(this);
            $("#txtChangeProductName").val($(currentProduct).text());
            $("#txtChangeProductToBuy").val($(currentProduct).next().text());
            $("#txtChangeProductAmount").val($(currentProduct).next().next().text());

            var switchToBuy = $("#txtChangeProductToBuy").data("kendoMobileSwitch");

            switchToBuy.check($(currentProduct).next().text() == "true");

        });
        alert('List has been reloaded with ' + g5.knownProducts.length + ' products.');
    }
};


var $has = {  
    touch: "ontouchend" in document,
    orientation: "onorientationchange" in window,
    geolocation: typeof navigator.geolocation != "undefined",
    transitions: "WebKitTransitionEvent" in window,
    canvas: !!document.createElement("canvas").getContext,
    audio: !!document.createElement("audio").canPlayType,
    localStorage: "localStorage" in window
     
};

